#include "../afw.h"

using namespace one_rag::impl;
using namespace one_rag;

DataFile::DataFile():_hf(INVALID_HANDLE_VALUE)
{
}

DataFile::~DataFile()
{
  if(_hf != INVALID_HANDLE_VALUE)
    CloseHandle(_hf);
}

bool DataFile::Open(const oschar* fileName,unsigned flags)
{
  if(_hf != INVALID_HANDLE_VALUE)
    CloseHandle(_hf);
  DWORD access = GENERIC_READ;
  DWORD shareMode = FILE_SHARE_READ|FILE_SHARE_DELETE;
  DWORD disposition = OPEN_EXISTING;
  if(flags & write)
    access |= GENERIC_WRITE;
  if(flags & allowwrite)
    shareMode |= FILE_SHARE_WRITE;
  if(flags & create)
    disposition = OPEN_ALWAYS;
  _hf = CreateFile(fileName,access,shareMode,NULL,disposition,FILE_ATTRIBUTE_NORMAL,0);
  return _hf != INVALID_HANDLE_VALUE;
}

long DataFile::Read(void* buf,long len)
{
  if(len <0)
    len=1024*1024;
  DWORD dw=0;
  BOOL ret = ReadFile(_hf,buf,len,&dw,NULL);

  return ret?dw:-1;
}

long DataFile::Size()
{
  DWORD dw = GetFileSize(_hf,NULL);
  return dw;
}
